import { defineStore } from 'pinia'

import { useApi } from '/@/api'
import router, { setRoutes, menuOptions } from '/@/router'
import { useCache } from '/@/cache'
import { TOKEN_KEY, REFRESH_TOKEN_KEY, ROUTES_IGNORE } from '/@/config'

export const useStore = defineStore({
  id: 'app',
  state: () => ({
    userInfo: {},
    meta: {
      ticket_source: [],
      menus: []
    }
  }),
  getters: {
    isLogined: state => state.userInfo && state.userInfo.id !== undefined,
    menus: state => state.meta.menus
  },
  actions: {
    async getUserInfo() {
      const { code, data } = await useApi()
        .get('info', null, { authorize: true, slient: true })

      if (code === 0) {
        this.setUser(data)

        if (router.currentRoute?.value.name === 'Login') {
          router.push('/')
        }
      } else if (router.currentRoute?.value.name !== 'Login') {
        router.push('/login')
      }

      return data
    },
    setUser(user) {
      if (!user || user.id === undefined) {
        useCache().removeItem(TOKEN_KEY)
        useCache().removeItem(REFRESH_TOKEN_KEY)
        return this.userInfo = {}
      }
      if (user?.role?.role) {
        setRoutes(ROUTES_IGNORE[user.role.role])
      }

      this.userInfo = user || {}
    },
    setMenus(menus) {
      this.meta.menus = menus || []
    }
  }
})
